<template>
  <div class="app-container">

    <el-breadcrumb>
      <el-breadcrumb-item :to="{path:'/index'}">首页</el-breadcrumb-item>
      <el-breadcrumb-item>个人资料</el-breadcrumb-item>
    </el-breadcrumb>

    <el-divider></el-divider>

    <br>
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="原始密码" prop="oldPassword">
        <el-input v-model="form.oldPassword" type="password"></el-input>
      </el-form-item>
      <el-form-item label="修改密码" prop="newPassword">
        <el-input v-model="form.newPassword" type="password"></el-input>
      </el-form-item>
      <el-form-item label="再次输入" prop="confirmPassword">
        <el-input v-model="form.confirmPassword" type="password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="update">修改</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    let validator1 = (rule, value, callback) => {
      if (value === this.form.oldPassword) {
        callback(new Error())
      } else {
        callback()
      }
    }
    let validator2 = (rule, value, callback) => {
      if (value !== this.form.newPassword) {
        callback(new Error())
      } else {
        callback()
      }
    }
    return {
      form: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      rules: {
        oldPassword: [
          {required: true, message: '请输入原始密码', trigger: 'blur'},
          {min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur'}
        ],
        newPassword: [
          {required: true, message: '密码不能为空', trigger: 'blur'},
          {min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur'},
          {validator: validator1, message: "修改后的密码不能与原始密码相同", trigger: 'blur'}
        ],
        confirmPassword: [
          {required: true, message: '密码不能为空', trigger: 'blur'},
          {validator: validator2, message: "两次密码需要相同", trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    update() {
      this.$refs['form'].validate((valid) => {
        if (!valid) {
          this.$message({
            type: 'error',
            message: '请正确填写参数'
          });
          return false;
        }
        this.$message({
          type: 'success',
          message: '密码修改成功'
        })
        this.form = {
          oldPassword: '',
          newPassword: '',
          confirmPassword: ''
        }
        setTimeout(() => {
          location.reload()
        }, 1000)
      });
    },
    reset() {
      this.$refs['form'].resetFields()
    }
  }
}
</script>

<style scoped>

</style>